<template>
  <div class="electrical-parmas">
    <div class="parmas-tabs">
      <div class="tab-group clearfloat">
        <span v-on:click="changeParmSearch(1)" v-bind:class="{active: parmSearch == 1}">实时</span>
        <span v-on:click="changeParmSearch(2)" v-bind:class="{active: parmSearch == 2}">历史</span>
      </div>
    </div>
    <div class="parmas-div" v-if="parmSearch == 1">
      <div class="chart-head clearfloat">
        <span class="tit theme-front-color">电气参数</span>
        <div class="search-d">
          <span class="search-input theme-front-color">
            采集时间：{{currentTime}}
          </span>
        </div>
      </div>
      <div class="parmas-d clearfloat">
        <el-row>
          <el-col :span="4" v-for="(item,index) in itemList" :key="index">
            <div class="parmas-ul">
              <div class="parmas-h">{{item.name}}({{item.unit}})</div>
              <div v-for="(curdata,idx) in item.subItem" :key="idx" class="theme-front-color">
                <span class="theme-front-color">
                  <i class="dot orange-dot" v-if="idx == 0"></i>
                  <i class="dot green-dot" v-if="idx == 1"></i>
                  <i class="dot red-dot" v-if="idx == 2"></i>
                  {{curdata.collectName}}
                </span>
                - {{curdata.oval}}({{curdata.collectUnit}})
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="parmas-div" v-if="parmSearch == 2">
      <div class="chart-head clearfloat">
        <span class="tit theme-front-color">电气参数</span>
        <div class="search-d">
          <span class="theme-front-color">选择时间：</span>
          <el-date-picker type="date"
            size="small"
            v-model="parmSearchDate"
            :picker-options="pickerOptions1"
            placeholder="选择日期"
            @change="changeData()"
          ></el-date-picker>
        </div>
      </div>
      <div class="params-d">
        <div class="tab-group paramsd-tab clearfloat">
          <span v-for="(item,index) in itemList" :key="index" v-on:click="changeActiveParams(index)" v-bind:class="{active: activeParams == item.name}">{{item.name}}</span>
        </div>
        <div class="params-echart" >
          <div id="electric" :style="'height:'+(containerHeight/2-130)+'px'"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import * as echarts from 'echarts'
  import commondef from '@/utils/common'
  import * as Util from "@/utils";
  export default {
    data () {
      return {
        meterCode:'',
        enegcate_code: '023300',
        parmSearch: 1,
        parmSearchDate: new Date(),
        activeParams: 1,
        pickerOptions1: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          }
        },
        itemList: [],
        currentTime: '',
        historyFlag: false,
        circleProgressWidth: 120
      }
    },
    created(){
       this.getItemList();
    },
    methods: {
      //刷新数据
      refreshData(data){
        this.meterCode =data;
        this.lastSampleDate();
        if(this.itemList.length>0){
          this.activeParams = this.itemList[0].name;
        }
        this.historySampleData(true);
        this.historyFlag = false;
      },
      changeParmSearch(status) {
        this.parmSearch = status;
        if(status == 1){//实时参数获取
          this.lastSampleDate();
        }else{
          this.activeParams = this.itemList[0].name;
          this.showEcharts(this.itemList[0]);
        }
      },
      changeActiveParams(item) {
        this.activeParams = this.itemList[item].name;
        this.showEcharts(this.itemList[item]);
      },
      changeData(){
        this.historySampleData(true);
      },
      /**
       * 查询项
       */
      getItemList () {
        let params = {
          'meterType': '1' ,
          'state': '1',
          "customerId":this.$util.cookies.get('customer_id'),
          'page': 1,
          'limit': 10000,
        }
        this.$api.okhttp({
          //url: that.$http.adornUrl('/ecs/ecscollectitem/list'),
          url:this.$http.adornUrl('/ecs/ecscollectitem/elegrouplist'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then(res => {
          if(res && res.code === 0){
            this.itemList = [];
            for (var i = 0; i < res.list.length; i++) {
              this.itemList.push({
                name: res.list[i].groupName,
                prop:  res.list[i].collectTypes&& res.list[i].collectTypes!=""?res.list[i].collectTypes.split(','):[],
                unit:res.list[i].collectUnit})
            }
            this.getSubItemList();
          }
        });
      },
      /**
       * 查询子项
       */
      getSubItemList(){
        let params = {
          'meterType': '010000' ,
          'state': '1',
          "customerId":this.$util.cookies.get('customer_id'),
          'page': 1,
          'limit': 10000,
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/ecs/ecscollectitem/list'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then(res => {
          if(res && res.code === 0){
            if(res.page&&res.page.list&&res.page.list.length>0){
              this.itemList.forEach(ele=>{
                this.$set(ele,'subItem',[]);
                ele.subItem=[];
                if(ele.prop.length>0){
                  for(let i=0;i<ele.prop.length;i++){
                    res.page.list.forEach(element=>{
                      if(element.collectType==ele.prop[i]){
                        Object.assign(element,{oval:0})
                        ele.subItem.push(element);
                      }
                    })
                  }
                }
              })
            }
            this.lastSampleDate();
            this.historySampleData(false);
          }
        });
      },
      /**
       * 实时数据
       */
      lastSampleDate(){
        var that = this;
        var para = {
          meterCode: this.meterCode,
          customerId: this.$util.cookies.get("customer_id")
        }
        //  var apiurl = api.urlList.datavincent.raw.get_latestsample;//实时
        this.$api.okhttp({
          url: this.$http.adornUrl('/eda/datavincent.raw.get_latestsample'),
          method: 'post',
          data: this.$http.adornParams(para)
        }).then((ress) => {
            if (ress.code === 0) {
              let res = ress.data
              console.log(111,res)
              //成功
              if(res.sample&&res.sample.data&&res.sample.data.Params){

                this.currentTime = res.sample.data.CollectTime;
                console.log(2222, this.itemList)
                this.itemList.forEach(ele=>{
                  for(let i=0;i<ele.subItem.length;i++){
                    ele.subItem[i].oval=0;
                    for(let key in res.sample.data.Params){
                      if(ele.subItem[i].collectType==key){
                        this.$set(ele.subItem[i],'oval',res.sample.data.Params[key].oval);
                        //ele.subItem[i].oval = res.sample.data.Params[key].oval;
                      }
                    }
                    //console.log(ele.subItem[i].collectName,ele.subItem[i].oval);
                  }
                })
              }
              // //设置宽度
              // setTimeout(function(){
              //   var circleProgressWidth = document.getElementById('parmas-r') ? document.getElementById('parmas-r').clientWidth / 6 : 120;
              //   circleProgressWidth = parseInt(circleProgressWidth - 6, 10);
              //   circleProgressWidth = circleProgressWidth > 160 ? 160 : circleProgressWidth;
              //   that.circleProgressWidth = circleProgressWidth || 120;
              // }, 500);
            } else {
              that.$message.error("最新数据查询失败")
            }
          })
      },
      /**
       * 历史数据
       */
      historySampleData(changeDateFlag){
        var that = this;
        var para = {
          meterparas: [that.meterCode],
          begin: that.parmSearchDate.format('yyyy-MM-dd') + " 00:00:00",
          end: that.parmSearchDate.format('yyyy-MM-dd') + " 23:59:59",
          energytype: '',
          rule: '',
          page_no: 1,
          page_size: 1000,
          customerId: this.$util.cookies.get("customer_id")
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/eda/datavincent.raw.get_samples_begin_end'),
          method: 'post',
          data: this.$http.adornParams(para)
        }).then(res => {
          if (res.code === 0) {
              //实时数据电气参数对象 整合数据
              var data = res.data.samples || [];
              that.itemList.forEach(element=>{
                if(element.subItem && element.subItem.length>0){
                  for(let v=0;v< element.subItem.length;v++){
                    element.subItem[v].hisdata = [];
                    data.forEach(ele=>{
                      if(ele.Params[element.subItem[v].collectType]){
                        element.subItem[v].hisdata.push({
                          time:ele.Params[element.subItem[v].collectType].RTime,
                          OVal:ele.Params[element.subItem[v].collectType].OVal,
                        })
                      }
                    })
                  }
                }
              })
              //改变日期重新绘图
              if(changeDateFlag){
                let item = that.itemList.find(ele=>ele.name==that.activeParams);
                that.showEcharts(item);
              }
            } else {
              that.$message.error("历史数据查询失败")
            }
          })
      },
      showEcharts(item){
        if(!this.meterCode){
          return false;
        }
        var options = {
          grid: {
            left: 40,
            top: 40,
            right: 20,
            bottom: 40
          },
          legend: {
            top: 10,
            right: 20,
            itemWidth: 10,
            itemHeight: 10
          },
          color: ['#F5A623', '#2BD597', '#FD7D7D', '#708DE5'],
          xAxis: {
            type: 'category'
          },
          yAxis : {
            name: item.unit ? '单位 ' + item.unit : '',
            type: 'value',
            scale: true,
            splitNumber: 5
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(val, n) {
              var returnStr = "<div style='text-align:left;'>" +
                "时间：" + val[0].name + "<br/>";
              for (var i in val) {
                returnStr = returnStr +
                  "<span style='display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:" + val[i].color + "'></span>" +
                  val[i].seriesName + "：" + val[i].value + " "+ (item.unit?item.unit:'') +
                  "<br/>"
              }
              returnStr = returnStr + "</div>";
              return returnStr;
            }
          }
        };
        options.series = [];
        options.legend.data = [];
        var valueaxis = [];
        if(item.subItem&&item.subItem.length>0){

          item.subItem.forEach((element,index)=>{
            var valuedatas = [];
            if(element.hisdata&&element.hisdata.length>0){
              for(let v=0;v<element.hisdata.length;v++){
                  valuedatas.push(element.hisdata[v].OVal);
                  if(index==0){
                    valueaxis.push(element.hisdata[v].time);
                  }
              }
            }
            options.series.push({
              name: element.collectName!==undefined?element.collectName:'',
              data: valuedatas,
              type: 'line',
              lineStyle: {
                width: 3
              },
              itemStyle:{
                normal:{
                  lineStyle:{
                    width: 3
                  }
                }
              },
              smooth: true,
              label: {
                formatter: function(params){
                  if (params.value > 0) {
                    return params.value;
                  } else {
                    return '';
                  }
                }
              }
            });
            options.legend.data.push({
              name: element.collectName!==undefined?element.collectName:'',
              icon:'circle'
            });
          })
        }
        options.xAxis.data = valueaxis;
        //初始化图表
        setTimeout(function(){
          if(document.getElementById('electric')){
            let myChart = echarts.init(document.getElementById('electric'));
            myChart.clear();
            //画图
            myChart.setOption(options);
          }
        }, 500);
      }
    },
    computed: {
      containerHeight() {
        return Util.getClientHeight() - 143;
      }
    },
    watch: {

    },
    mounted () {
     //this.getItemList();
    }
  }
</script>

<style scoped lang="scss">
  @import "../../../assets/scss/_variables";

  /*标题*/
  .chart-head {
    margin-top: 10px;
  }

  .tit {
    float: left;
    font-size: 16px;
    line-height: 33px;
  }

  .search-d {
    float: right;
    font-size: 14px;
  }

  .search-d .tab-group {
    margin-top: 3px;
    float: left;
  }

  .search-input {
    margin-left: 20px;
  }

  /*tab*/
  .tab-group.small {
    display: inline-block;
  }

  .tab-group span {
    color: #9c9c9c;
    display: inline-block;
    padding: 4px 30px;
    font-size: 14px;
    float: left;
    cursor: pointer;
    border-top: 1px solid #ccc;
    border-bottom: 1px solid #ccc;
    border-left: 1px solid #ccc;
  }

  .tab-group span.active {
    color: #fff;
    background-color: #708DE5;
    border-color: #708DE5;
    box-shadow: -1px 0 0 0 #708DE5;
  }

  /* .tab-group span:first-child {
    border-left: 1px solid #ccc;
  } */

  .tab-group span:last-child {
    border-right: 1px solid #ccc;
  }

  .tab-group span:first-child {
    border-radius: 5px 0 0 5px;
  }

  .tab-group span:last-child {
    border-radius: 0 5px 5px 0;
  }

  .tab-group.small span {
    padding: 2px 15px;
    font-size: 12px;
  }

  /*小点*/

  .dot {
    margin: 2px 2px 2px 0;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    display: inline-block;
  }

  .orange-dot {
    background-color: #F5A623;
  }

  .green-dot {
    background-color: #2BD597;
  }

  .red-dot {
    background-color: #FD7D7D;
  }


  /*清除浮动代码*/

  .clearfloat:after {
    display: block;
    clear: both;
    content: "";
    visibility: hidden;
    height: 0
  }

  .clearfloat {
    zoom: 1
  }

  /*提示*/
  .note{
    padding: 20px;
    text-align:center;
    color:#666;
  }
  .params-echart  div {
    width: 100%;
  }
  .params-echart .note {
    height: 200px;
  }
  .note img{
    width: 140px;
  }
  /*页面*/
  .electrical-parmas {
    margin-top: 10px;
   /* background: $font-white; */
    border-radius: 5px 5px 0 0;
  }


  .parmas-tabs {
    text-align: left;
    border-bottom: 1px solid #708DE5;
  }

  .parmas-tabs .tab-group {
    margin-bottom: -1px;
  }

  .parmas-tabs .tab-group span:first-child {
    border-radius: 5px 0 0 0;
  }

  .parmas-tabs .tab-group span:last-child {
    border-radius: 0;
  }

  .parmas-tabs .tab-group span {
    background-color: #f2f2f2;
  }

  .parmas-tabs .tab-group span.active {
    background-color: #708DE5;
  }

  .parmas-div {
    padding: 15px 20px;
    margin-bottom: -20px;
  }

  .parmas-d .el-col {
    padding: 0px 6px;
  }

  .parmas-d .parmas-ul {
    border: 1px solid $shadow-color;
    border-radius: 8px 8px 0 0;
    min-height: 167px;
  }

  .parmas-ul .parmas-h {
    text-align: center;
    background-color: #eee;
    border-radius: 8px 8px 0 0;
  }

  .parmas-ul>div {
    text-align: left;
    font-size: 14px;
    padding: 6px 0;
    border-top: 1px solid $shadow-color;
    text-align: center;
  }
  .parmas-ul>div span{
    text-align: right;
    display:inline-block;
  }

  .parmas-rd {
    position: relative;
    display:inline-block;
  }

  .parmas-rd .progress-txt {
    position: absolute;
    top: 30%;
    left: 0;
    width: 100%;
    text-align: center;
  }

  .progress-txt .tt {
    color: #777;
  }

  .progress-txt .txt {
    font-weight: 900;
    color: $main-font-color;
  }
  .paramsd-tab {
    margin-top: 15px;
    margin-bottom: 10px;
  }
  .paramsd-tab span {
    padding: 4px;
    width: 80px;
  }

  .qualityd-tab span {
    padding: 4px;
    width: 100px;
  }
  @media screen and (min-width: 1400px) {
    .parmas-ul>div span{
      display: inline;
    }
    .parmas-ul>div span.allspan{
      width: 40%;
    }
    .progress-txt .tt{
      font-size: 12px;
    }
    .progress-txt .txt {
      font-size: 26px;
      line-height:40px;
    }
  }
  @media screen and (max-width: 1400px) {
    .parmas-ul>div span{
      margin-left:0.5rem;
    }
    .parmas-ul>div span.allspan{
      margin-left:2rem;
    }
    .progress-txt .tt{
      font-size: 12px;
    }
    .progress-txt .txt {
      font-size: 20px;
      line-height:40px;
    }
  }
</style>
